﻿using HBKY.Shop.Common;
using HBKY.Shop.Common.DB;
using HBKY.Shop.Common.Helper;
using HBKY.Shop.Common.LogHelper;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace HBKY.Shop.Extensions.ServiceExtensions
{
    /// <summary>
    /// SqlSugar 启动服务
    /// </summary>
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            //// 默认添加主数据库连接
            MainDb.CurrentDbConnId = Appsettings.Option("MainDB");

            // 把多个连接对象注入服务，这里必须采用Scope，因为有事务操作
            services.AddScoped<ISqlSugarClient>(o =>
            {
                // 连接字符串
                var listConfig = new List<ConnectionConfig>();
                // 从库
                var listConfig_Slave = new List<SlaveConnectionConfig>();
                BaseDBConfig.MutiConnectionString.Item2.ForEach(s =>
                {
                    listConfig_Slave.Add(new SlaveConnectionConfig()
                    {
                        HitRate = s.HitRate,
                        ConnectionString = s.Connection
                    });
                });

                BaseDBConfig.MutiConnectionString.Item1.ForEach(m =>
                {
                    listConfig.Add(new ConnectionConfig()
                    {
                        ConfigId = m.ConnId.ObjToString().ToLower(),
                        ConnectionString = m.Connection,
                        DbType = (DbType)m.DbType,
                        IsAutoCloseConnection = true,
                        //IsShardSameThread = false,
                        AopEvents = new AopEvents
                        {
                            OnLogExecuting = (sql, p) =>
                            {
                                if (Appsettings.Option("AppSettings", "SqlAOP", "Enabled").ObjToBool())
                                {
                                    Parallel.For(0, 1, e =>
                                    {
                                        if (sql.StartsWith("SELECT"))
                                        {
                                            Console.ForegroundColor = ConsoleColor.Green;
                                        }
                                        if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
                                        {
                                            Console.ForegroundColor = ConsoleColor.White;
                                        }
                                        if (sql.StartsWith("DELETE"))
                                        {
                                            Console.ForegroundColor = ConsoleColor.Blue;
                                        }

                                        var logContent = String.Join("\r\n", new string[]
                                        {
                                                "SqlLog", GetParas(p),
                                                $"【SQL语句】：{sql}",
                                                $"【ConfigId】：{m.ConnId.ObjToString().ToLower()}",
                                                $"【DbType】：{(DbType) m.DbType}",
                                        });

                                        //线上不需要打控制台sql日志
                                        if (!EnvHelper.IsOnline) Console.WriteLine(logContent);

                                        LogManagerNlog.LogInformation(logContent);
                                    });
                                }
                            }
                        },
                        MoreSettings = new ConnMoreSettings()
                        {
                            IsAutoRemoveDataCache = true
                        },
                        // 从库
                        SlaveConnectionConfigs = listConfig_Slave,
                        //InitKeyType = InitKeyType.SystemTable
                    }
                   );
                });
                return new SqlSugarClient(listConfig);
            });
        }

        private static string GetParas(SugarParameter[] pars)
        {
            StringBuilder sb = new StringBuilder();
            if (pars.Length > 0)
            {
                sb.Append("【SQL参数】：");
                foreach (var param in pars)
                {
                    sb.Append($"{param.ParameterName}:{param.Value}\n");
                }

                sb.Remove(sb.Length - 1, 1);
            }

            return sb.ToString();
        }
    }
}
